package edu.maine.usm.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;

import edu.maine.usm.rpc.EnrollmentServiceAsync;

public class EnrollmentView extends Composite {

	private static EnrollmentViewUiBinder uiBinder = GWT
			.create(EnrollmentViewUiBinder.class);
	
	@UiField Button enrollBtn;
	@UiField InputElement externalIdentifier;
	@UiField InputElement scheduleName;
	@UiField DivElement statusMsg;

	private EnrollmentServiceAsync service;

	interface EnrollmentViewUiBinder extends UiBinder<Widget, EnrollmentView> {
	}

	public EnrollmentView(EnrollmentServiceAsync service) {
		this.service = service;
		initWidget(uiBinder.createAndBindUi(this));
	}
	
	@UiHandler("enrollBtn")
	public void handleClick(ClickEvent event) {
		toggleElements(false);
		statusMsg.setInnerHTML("Enrolling...");
		
		service.enrollInSchedule(scheduleName.getValue(), externalIdentifier.getValue(), new AsyncCallback<Void>() {

			public void onFailure(Throwable caught) {
				statusMsg.setInnerText("Error sending request to enroll");
				toggleElements(true);
			}

			public void onSuccess(Void result) {
				statusMsg.setInnerHTML("Successfully enrolled!");
				toggleElements(true);
			}
		});
	}

	private void toggleElements(boolean enabled) {
		enrollBtn.setEnabled(enabled);
		externalIdentifier.setDisabled(!enabled);
		scheduleName.setDisabled(!enabled);
	}

}
